package leetcode;

import java.util.ArrayList;
import java.util.List;

/**
 * @Project : AlgorithmLearning
 * @Package : Leetcode
 * @File : Q0054.java
 * @Author : WangRuoyu
 * @Date 2023/11/6 20:55
 */


public class Q0054 {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> res = new ArrayList<>();

        int[] dx = {0, 1, 0, -1};
        int[] dy = {1, 0, -1, 0};

        int i = 0;
        int j = 0;
        int k = 0;
        int xMax = matrix.length - 1;
        int xMin = 0;
        int yMax = matrix[0].length - 1;
        int yMin = 0;

        while (res.size() < matrix.length * matrix[0].length) {
            while (i >= xMin && i <= xMax && j >= yMin && j <= yMax) {
                res.add(matrix[i][j]);
                i += dx[k];
                j += dy[k];
            }
            i -= dx[k];
            j -= dy[k];
            if (k == 0) {
                xMin++;
            } else if (k == 1) {
                yMax--;
            } else if (k == 2) {
                xMax--;
            } else {
                yMin++;
            }
            k = (k + 1) % 4;
            i += dx[k];
            j += dy[k];
        }
        return res;
    }

    public static void main(String[] args) {
        Q0054 sl = new Q0054();
        int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        System.out.println(sl.spiralOrder(matrix));
    }
}